package controller

import (
	"crypto/sha1"
	"encoding/hex"
	"fmt"
	"net/http"
	"sort"

	"github.com/gin-gonic/gin"
)

const token = "hnsjb"

func Test1(c *gin.Context) {
	http.HandleFunc("/api/wxapi/message/Test", handleWechatServer)
	fmt.Println("Server started at :8080")
	http.ListenAndServe(":8080", nil)
}

func handleWechatServer(w http.ResponseWriter, r *http.Request) {
	// 获取URL参数
	signature := r.URL.Query().Get("signature")
	timestamp := r.URL.Query().Get("timestamp")
	nonce := r.URL.Query().Get("nonce")
	echostr := r.URL.Query().Get("echostr")

	// 验证签名
	if verifySignature(signature, timestamp, nonce) {
		// 签名验证通过，返回echostr
		w.Write([]byte(echostr))
	} else {
		http.Error(w, "Invalid signature", http.StatusBadRequest)
	}
}

func verifySignature(signature, timestamp, nonce string) bool {
	// 1. 字典序排序
	strs := []string{nonce, timestamp, token}
	sort.Strings(strs)

	// 2. 拼接字符串
	combined := ""
	for _, str := range strs {
		combined += str
	}

	// 3. SHA1加密
	h := sha1.New()
	h.Write([]byte(combined))
	sha1Hash := hex.EncodeToString(h.Sum(nil))

	// 4. 比较签名
	return sha1Hash == signature
}
